package com.jerry.base.thread;

import lombok.extern.slf4j.Slf4j;

/**
 * User: Jerry
 * Date: 2024/2/24
 * Time: 14:21
 * Description:
 */
@Slf4j
public class Money {

    public static void main(String[] args) {
        Bank bank = new Bank();
        User user1 = new User(bank, 100, "用户1");
        User user2 = new User(bank, 100, "用户2");
        User user3 = new User(bank, 100, "用户3");
        User user4 = new User(bank, 100, "用户4");

        user1.start();
        user2.start();
        user3.start();
        user4.start();

        log.info("银行余额：{}", bank.getBalance());
    }
}

@Slf4j
class Bank {

    private int balance = 10000;

    public synchronized boolean withdraw(int amount, String userName) {
        if (balance >= amount) {
            balance -= amount;
            log.info("{}取款{}成功，银行剩余：{}", userName, amount, balance);
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            return true;
        } else {
            log.info("{}正在取钱，银行余额不足", userName);
            return false;
        }
    }

    public int getBalance() {
        return balance;
    }

}

@Slf4j
class User extends Thread {
    private Bank bank;

    private int amount;

    private int sum;

    private String name;

    public User(Bank bank, int amount, String name) {
        this.bank = bank;
        this.amount = amount;
        this.name = name;
    }

    @Override
    public void run() {
        while (true) {
            boolean success = bank.withdraw(amount, name);
            if (!success) {
                break;
            }
            sum += 100;
        }
        log.info("{}一共取了{}", name, sum);
    }
}



